import {
  imageLiveDetails,
  imageLiveImages,
  imageLiveComment,
  sendComment,
  likeLive,
  signOutLive,
  likeComment
} from '../../apis/live';
import {
  splicing,
  formatTime
} from '../../utils/util';
const app = getApp();

let interval = null;

Page({
  data: {
    navIndex: 0,
    liveDetails: {},
    commentBoxShow: false,
    authorizationShow: false,
    callBackType: '',
    imageList: [],
    firstTime: '',
    imageTotal: 0,
    imagePageNum: 1,
    imageHaveMore: true,
    imageRequest: false,
    commentRequest: false,
    commentList: [],
    commentTotal: 0,
    commentPageNum: 1,
    commentHaveMore: true
  },

  onLoad(options) {
    this.setData({
      ...options
    });
    this.getLiveDetails(options.liveId);
    this.getLiveDetailsComment(1);
    this.getLiveDetailsImages({
      pageNum: 1,
      pageSize: 10,
      type: 1,
      refreshTime: formatTime(new Date(), 'data')
    });
  },

  onShow() {
    interval = setInterval(() => {
      this.getLiveDetailsImages({
        pageNum: 1,
        pageSize: this.data.imagePageNum * 10,
        type: 1,
        refreshTime: formatTime(new Date(), 'data')
      }, 'refresh');
    }, 5000);
  },

  onHide() {
    clearInterval(interval);
    interval = null;
  },

  onUnload() {
    this.signOutLive();
    clearInterval(interval);
    interval = null;
  },

  onShareAppMessage() {
    return {
      title: this.data.liveDetails.name,
      path: `/pages/liveDetails/index?liveId=${this.data.liveId}`,
      imageUrl: this.data.liveDetails.coverImg
    }
  },

  // 页面下拉刷新
  onPullDownRefresh() {
    this.setData({
      commentPageNum: 1,
      commentHaveMore: true
    });
    this.getLiveDetails(this.data.liveId);
    this.getLiveDetailsComment(1);
  },
  // 页面触底
  onReachBottom() {
    if (this.data.navIndex === 1 && this.data.commentHaveMore) {
      this.getLiveDetailsComment(this.data.commentPageNum + 1, 'load');
    } else if (this.data.navIndex === 0 && this.data.imageHaveMore) {
      this.getLiveDetailsImages({
        pageNum: this.data.imagePageNum + 1,
        pageSize: 10,
        type: 2,
        refreshTime: this.data.firstTime
      });
    };
  },

  // 直播详情
  getLiveDetails(liveId) {
    imageLiveDetails(liveId).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        data.coverImg = splicing(data.coverImg);
        this.setData({
          liveDetails: data
        });
      };
    });
  },
  /** 
   * 直播图片
   *  data: {
   *    pageNum: 页码
   *    pageSize: 数量
   *    type: 1-刷新    2-加载
   *    refreshTime: type=1时传当前时间   type=2时传获取第一页的时间
   *  }
   */
  getLiveDetailsImages(data, type) {
    if (this.data.imageRequest) return
    this.setData({
      imageRequest: true
    });
    imageLiveImages(this.data.liveId, data).then(res => {
      this.setData({
        imageRequest: false
      });
      if (res.data.code === 200) {
        if (type != 'refresh') {
          this.setData({
            imagePageNum: data.pageNum
          });
        };
        let {
          rows,
          total
        } = res.data;
        rows.forEach(v => {
          v.image = splicing(v.image);
        });
        if (data.type === 1) {
          this.setData({
            imageList: rows,
            imageTotal: total
          });
          if (type != 'refresh') {
            this.setData({
              firstTime: data.refreshTime
            });
          };
        } else {
          this.data.imageList.push(...rows);
          this.setData({
            imageList: this.data.imageList
          });
        };

        if (this.data.imageList.length === total) {
          this.setData({
            imageHaveMore: false
          });
        } else {
          this.setData({
            imageHaveMore: true
          });
        };
      };
    });
  },

  // 查看图片
  previewImg(e) {
    let {
      src
    } = e.currentTarget.dataset;
    wx.previewImage({
      urls: this.data.imageList.map(v => v.image),
      current: src
    }, true);
  },

  // 直播评论
  getLiveDetailsComment(pageNum, type) {
    if (this.data.commentRequest) return
    this.setData({
      commentRequest: true
    });
    imageLiveComment(this.data.liveId, pageNum, 10).then(res => {
      wx.stopPullDownRefresh();
      this.setData({
        commentRequest: false
      });
      if (res.data.code === 200) {
        this.setData({
          commentPageNum: pageNum
        });
        let {
          rows,
          total
        } = res.data;
        this.setData({
          commentTotal: total
        });
        rows.forEach(v => {
          v.createTime = formatTime(v.createTime);
        });
        if (type === 'load') {
          rows.forEach(v => {
            this.data.commentList.push(v);
            this.setData({
              commentList: this.data.commentList
            });
          });
        } else {
          this.setData({
            commentList: rows
          });
        };

        if (this.data.commentList.length === total) {
          this.setData({
            commentHaveMore: false
          });
        };
      };
    });
  },

  // 发送评论
  sendComment(e) {
    let {
      value
    } = e.detail;
    wx.showLoading({
      title: '提交中...',
      mask: true
    });
    sendComment(this.data.liveId, value).then(res => {
      wx.hideLoading();
      if (res.data.code === 200) {
        wx.showToast({
          title: '评论成功',
          duration: 1000,
          icon: 'success',
          mask: true
        });
        this.setData({
          commentBoxShow: false
        });
        this.getLiveDetailsComment(this.data.commentPageNum);
      };
    });
  },
  // 授权回调
  callBack(e) {
    let {
      type
    } = e.detail;
    if (type === 'comment') {
      this.showCommentBox();
    } else {
      this.goodLive();
    };
  },

  // 点赞直播
  goodLive() {
    if (!app.globalData.isAuthorization) {
      this.setData({
        authorizationShow: true,
        callBackType: 'like'
      });
      return
    };
    wx.showLoading({
      title: '请稍候...',
      mask: true
    });
    likeLive(this.data.liveId).then(res => {
      wx.hideLoading();
      if (res.data.code === 200) {
        if (this.data.liveDetails.hasLike) {
          wx.showToast({
            title: '取消成功',
            duration: 1000,
            icon: 'success',
            mask: true
          });
          this.setData({
            'liveDetails.hasLike': false,
            'liveDetails.likeNum': this.data.liveDetails.likeNum - 1
          });
        } else {
          wx.showToast({
            title: '点赞成功',
            duration: 1000,
            icon: 'success',
            mask: true
          });
          this.setData({
            'liveDetails.hasLike': true,
            'liveDetails.likeNum': this.data.liveDetails.likeNum + 1
          });
        };
      };
    });
  },
  // 点赞评论
  likeComment(e) {
    let {
      id,
      index
    } = e.currentTarget.dataset;
    likeComment(id).then(res => {
      if (res.data.code === 200) {
        if (this.data.commentList[index].hasLike) {
          wx.showToast({
            title: '取消成功',
            icon: 'success',
            duration: 1000
          });
          this.setData({
            [`commentList[${index}].hasLike`]: false,
            [`commentList[${index}].likeNum`]: this.data.commentList[index].likeNum - 1
          });
        } else {
          wx.showToast({
            title: '点赞成功',
            icon: 'success',
            duration: 1000
          });
          this.setData({
            [`commentList[${index}].hasLike`]: true,
            [`commentList[${index}].likeNum`]: this.data.commentList[index].likeNum + 1
          });
        };
      };
    });
  },

  // 退出直播
  signOutLive() {
    signOutLive(this.data.liveId).then(res => {
      if (res.data.code === 200) {

      };
    });
  },

  changeNav(e) {
    let {
      index
    } = e.currentTarget.dataset;
    this.setData({
      navIndex: index
    });
  },

  // 显示评论输入
  showCommentBox() {
    if (!app.globalData.isAuthorization) {
      this.setData({
        authorizationShow: true,
        callBackType: 'comment'
      });
      return
    };
    this.setData({
      commentBoxShow: true
    });
  }
})